local skill = fk.CreateSkill {
  name = "#ling__inaccurate_spear_skill",
  tags = { Skill.Compulsory },
  attached_equip = "ling__inaccurate_spear",
}

Fk:loadTranslationTable{
  ["#ling__inaccurate_spear_skill"] = "不正矛",
  ["ling__inaccurate_spear_draw"] = "%dest摸两张牌",
  ["ling__inaccurate_spear_discard"] = "%dest弃两张牌",
}

skill:addEffect(fk.PreCardUse, {
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(skill.name) and data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    data.extra_data = data.extra_data or {}
    data.extra_data.bypass_times = true
    local new_tos = table.random(data.card:getAvailableTargets(player, data.extra_data), #data.tos)
    room:sortByAction(new_tos)
    data.tos = new_tos
    new_tos = table.map(new_tos, Util.IdMapper)
    data.extra_data.inaccurate_spear = {
      from = player,
      last_tos = player:getTableMark(skill.name),
      new_tos = new_tos,
    }
    room:setPlayerMark(player, skill.name, new_tos)
  end,
})

skill:addEffect(fk.Damage, {
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    if target == player and player:hasSkill(skill.name) and
      data.card and data.card.trueName == "slash" then
      local e = player.room.logic:getCurrentEvent().parent
      while e do
        if e.event == GameEvent.UseCard then
          local use = e.data
          if use.extra_data and use.extra_data.inaccurate_spear and
            use.extra_data.inaccurate_spear.from == player and
            table.contains(use.extra_data.inaccurate_spear.new_tos, data.to.id) then
            event:setCostData(self, {tos = {data.to}, extra_data = use.extra_data.inaccurate_spear})
            return true
          end
        end
        e = e.parent
      end
    end
  end,
  on_use = function (self, event, target, player, data)
    local room = player.room
    if not data.to.dead then
      if room:askToChoice(player, {
        choices = {
          "ling__inaccurate_spear_draw::"..data.to.id,
          "ling__inaccurate_spear_discard::"..data.to.id,
        },
        skill_name = skill.name,
      }):startsWith("ling__inaccurate_spear_draw") then
        data.to:drawCards(2, skill.name)
      else
        room:askToDiscard(data.to, {
          min_num = 2,
          max_num = 2,
          include_equip = true,
          skill_name = skill.name,
          cancelable = false,
        })
      end
    end
    local cards = table.filter(player:getEquipments(Card.SubtypeWeapon), function (id)
      return Fk:getCardById(id).name == skill.attached_equip
    end)
    if not player.dead and #cards > 0 and event:getCostData(self).extra_data and
      table.contains(event:getCostData(self).extra_data.last_tos, data.to.id) then
      room:throwCard(cards, skill.name, player, player)
    end
  end,
})

return skill
